package com.situ.blog.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils2 {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //工具类私有(必写)
    private JDBCUtils2(){}

    //静态代码块，在类加载的时候只会执行一次
    //静态方法类加载自动调用
    static {
        try { //对驱动的处理
            //1.通过当前的类获取类加载器
            ClassLoader classLoader = JDBCUtils2.class.getClassLoader();
            //2.通过类加载器的方法获取输入流
            //使用db.properties工具类配置文件
            InputStream inputStream = classLoader.getResourceAsStream("db.properties");
            //3.创建一个Properties对象
            Properties properties = new Properties();
            properties.load(inputStream);
            //4.获取配置文件中参数的值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //1、加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //2、获得连接对象Connection
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    //6.关闭连接
    //为建立两个表之间的联系：传递参数
    public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
